//index.js
//获取应用实例
const app = getApp()
var utils = require('../../utils/util.js');
var amapFile = require('../../utils/amap-wx.js');
Page({
  data: {
    currentTab: "all",
    navScrollLeft: 0,
    currentTab1: 0,


    navScrollLeft1: 0,
    ishide: 0,
    sc_id: "",
    number: 0,
    isback: false,
    isCoupon: true,
    isshouquan: true,
    info: true,
	currentPage: 1,
  },
  bindBanner: function(e) {
    var index = e.currentTarget.dataset.index;
    var that = this;
    var current = that.data.one_slider[index];
    switch (current.type) {
      case 1:

        for (index in that.data.activityData) {
          if (current.be_id == that.data.activityData[index].id) {
            var banner = that.data.activityData[index].banner;
            break;
          }
        }
        var url = '/pages/solarclassification/solarclassification?id=' + current.be_id + '&banner=' + banner;
        break;
      case 2:
        var url = '/pages/commoditydetails/commoditydetails?id=' + current.be_id;
        break;
    }
    wx.navigateTo({
      url,
    });
  },
  onKillPrice: function() {
    wx.navigateTo({
      url: '/pages/killPrice/killPrice?id=2&banner=http://qiniu.23fu.cc/eb65c0edb0893d35c8fa11fc0d5bf511.png',
    })
  },
  onShow: function(e) {
    var that = this;
    utils.setTabBarBadge();
    if (app.globalData.key !== undefined) {

      that.lll();
      that.lll2();
    }
    // console.log(app.globalData.addressName)
    if (app.globalData.addressName != undefined) {
      that.setData({
        addressName: app.globalData.addressName
      })
    }
  },
  onLoad: function(options) {
    var that = this;
    console.log('首页onload', options)
    that.setData({
      q: options.q ? options.q : null,
      redirect: options.redirect ? options.redirect : null,
    }, function() {
      that._init();
    })
  },
  _init: function() {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({
      key: "e62e6706033bcb067640317902ef53ad"
    });
    myAmapFun.getRegeo({
      success: function(data) {
        that.setData({
          addressName: data[0].regeocodeData.formatted_address
        })
      },
      fail: function(err) {
        console.log(11);
        that.setData({
          isshouquan: false
        })
      },
    });
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth,
          screenHeight: res.screenHeight
        })
      },
    })
    if (app.globalData.key !== undefined) {
      that._load()
    } else {
      //登录后获取店铺列表
      var share_id = '';
      if (that.data.q) {
        let q = utils.getJson(decodeURIComponent(that.data.q));
        if (!q.member_id) {
          //爱心分享邀请用户
          share_id = q.member_id;
        }
      }

      app.makeLogin((res) => {
        that._load()
      }, share_id);
    }
  },
  _load: function() {
    var that = this;
    that.couponList();
    that.categorylist();
    that.sliderlist();
    that.systemlist();
    that.activity();
    that.fine();
    that.advance();
    that.spikeclass();
    that.salegoods();
    that.indexgoodslist()
    that.lll();
    that.lll2();
    that.personalInfo();
	that.goodslist();

    if (that.data.q) {
      let q = utils.getJson(decodeURIComponent(that.data.q));
      var type = q.type;
      console.log('qqqqqqqqqqqq', q)
      if (type == 1) {
        //拼团
        var id = q.id;
        var url = '/pages/allssembledetails/allssembledetails?id=' + id;
        wx.navigateTo({
          url: url
        })
        return;
      } else if (type == 2) {
        //砍价
        var order_id = q.order_id;
        var id = q.id;
        var url = '/pages/killPrice/details?id=' + id + '&order_id=' + order_id;
        wx.navigateTo({
          url: url
        })
        return;
      } else if (type == 3) {
        //普通商品
        var id = q.id;
        var url = '/pages/commoditydetails/commoditydetails?id=' + id;
        wx.navigateTo({
          url: url
        });
        return;
      }
    }
    if (that.data.redirect) {
      console.log('unescape(that.data.redirect),', unescape(that.data.redirect))
      wx.navigateTo({
        url: unescape(that.data.redirect),
      })
    }
  },
  //授权完之后
  handler: function(e) {
    var that = this;
    console.log("sdjkfl")
    if (e.detail.authSetting['scope.userLocation']) {
      var myAmapFun = new amapFile.AMapWX({
        key: "e62e6706033bcb067640317902ef53ad"
      });
      myAmapFun.getRegeo({
        success: function(data) {
          that.setData({
            addressName: data[0].regeocodeData.formatted_address
          })
          console.log(data[0].regeocodeData.formatted_address);
          that.setData({
            isshouquan: true
          })
        },
        fail: function(err) {
          console.log(11);
          that.setData({
            isshouquan: false
          })
        },
      });
      // wx.getLocation({
      //     type: 'gcj02',
      //     success: function(res) {
      //         var latitude = res.latitude
      //         var longitude = res.longitude
      //         var speed = res.speed
      //         var accuracy = res.accuracy

      //         var markersData = {
      //             latitude: latitude, //纬度
      //             longitude: longitude, //经度
      //             key: that.data.MapKey
      //         };
      //         var addArr = [];
      //         var myAmapFun = new amapFile.AMapWX({
      //             key: "e62e6706033bcb067640317902ef53ad"
      //         });
      //         myAmapFun.getRegeo({
      //             success: function(data) {
      //                 that.setData({
      //                     addressName: data[0].regeocodeData.formatted_address
      //                 })
      //                 console.log(data[0].regeocodeData.formatted_address);
      //             }

      //         });
      //     }
      // })
      // that.setData({
      //     isshouquan: true
      // })
      //  console.log(that.data.isshouquan)
    } else {
      console.log("2222222222222")
    }



  },
  //我的个人信息
  personalInfo: function(e) {
    var that = this;
    utils.http("/api/v1/member/index", {}, function(res) {
      that.setData({
        info: res.datas
      }, function() {
        var existTime = that.data.systemData.n_hour_show_identify * (60 * 60);
        var last_login_time = wx.getStorageSync('last_login_time') ? wx.getStorageSync('last_login_time') : 0;
        var timestamp = Date.parse(new Date()) / 1000;
        console.log(last_login_time + existTime)
        //授权已过期，重新弹窗授权
        if (res.datas && (last_login_time + existTime) <= timestamp) {
          that.setData({
            info: ''
          })
        }
        console.log('获取的用户信息====', res.datas)
      })
      if (that.data.info.nickname != "") {
        if (that.data.coupon.have_state == 0) {
          that.setData({
            isCoupon: false
          })
        }
      }
    })
  },
  //分类商品切换接口
  categorylist: function(e) {
    var that = this;
    utils.http("/api/v1/category/category_list", {}, function(res) {
      that.setData({
        navData: res.datas
      })
    })
  },
  //轮播图接口   每日特价轮播 接口
  sliderlist: function(e) {
    var that = this;
    utils.http("/api/v1/common/slider_list", {}, function(res) {
      that.setData({
        one_slider: res.datas.one_slider,
        top_slider: res.datas.top_slider
      })
    })
  },
  //公告数据接口
  systemlist: function(e) {
    var that = this;
    utils.http("/api/v1/common/system", {}, function(res) {
      that.setData({
        systemData: res.datas
      })
    })
  },
  ////时令水果、圣诞来临、元旦到了、新年新气象接口
  activity: function(e) {
    var that = this;
    utils.http("/api/v1/index/activity_list", {}, function(res) {
      that.setData({
        activityData: res.datas
      })
    })
  },
  //精品选择接口
  fine: function(e) {
    var that = this;
    utils.http("/api/v1/index/fine_list", {}, function(res) {
      that.setData({
        fineData: res.datas
      })
      wx.setStorageSync('fineData', res.datas)
    })
  },
  //预售商品
  advance: function() {
    var that = this;
    utils.http("/api/v1/goods/goods_list", {
      if_zero: 0,
      if_advance: 1,
      page: 1
    }, function(res) {
      that.setData({
        advance: res.datas
      })
    })
  },
  //秒杀分段  时间接口
  spikeclass: function(e) {
    var that = this;
    utils.http("/api/v1/index/spike_class_list", {}, function(res) {
      that.setData({
        spikeData: res.datas
      })
      if (res.datas.length > 0) {
        that.spikegoods(res.datas[0].id);
      }
    })
  },
  //秒杀商品列表 接口
  spikegoods: function(scId) {
    var that = this;
    utils.http("/api/v1/index/spike_goods_list", {
      sc_id: scId
    }, function(res) {
      that.setData({
        spikegoodsData: res.datas
      })
    })
  },
  //热销商品 接口
  salegoods: function(e) {
    var that = this;
    utils.http("/api/v1/index/sale_goods_list", {}, function(res) {
      that.setData({
        salegoods: res.datas
      })
    })
  },

  //城市选择器
  onSwitchCityTap: function(e) {
    wx.navigateTo({
      url: '../switchcity/switchcity',
    })
  },
  switchNav(event) {
    var cur = event.currentTarget.dataset.current;
    var id = event.currentTarget.dataset.id;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur,
		categoryId:id
      })
    }
    this.ategoryGoodsList();
  },
  //点击分类全部
  switchNavAll: function(e) {
    var that = this;
    var all = "all";
    that.setData({
      currentTab: all
    })
  },
  switchNav1(event) {
    var cur = event.currentTarget.dataset.current;
    var id = event.currentTarget.dataset.id;
    var status = event.currentTarget.dataset.status;
    console.log(status)
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft1: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab1 == cur) {
      return false;
    } else {
      this.setData({
        currentTab1: cur,
        status: status
      })
    }
    this.spikegoods(id);
  },

  //时令水果、圣诞来临、元旦到了、新年新气象
  noWaresTap: function(e) {
    wx.navigateTo({
      url: '../solarclassification/solarclassification?id=' + e.currentTarget.dataset.id + "&banner=" + e.currentTarget.dataset.banner,
    })
  },
  //0元尝鲜
  onZeroGoods: function(e) {
    wx.navigateTo({
		url: '../solarclassification/solarclassification?type=1&banner=/images/banner2.jpg',
    })
  },
  //搜索
  onSearchTap: function(e) {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  //商品详情
  noFrutisDetailsTap: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../commoditydetails/commoditydetails?id=' + id,
    })
  },
  //附近好店
  onStorenearbyTap: function(e) {
    wx.navigateTo({
      url: '../storenearby/storenearby',
    })
  },
  //拼着更省
  onAllssembleTap: function(e) {
    wx.navigateTo({
      url: '../allssemble/allssemble',
    })
  },
  //一起众筹
  onCrowDraisingTap: function(e) {
    wx.navigateTo({
      url: '../crowdraising/crowdraising',
    })
  },
  //每日配送
  onDailydeLiveryTap: function(e) {
    wx.navigateTo({
      url: '../dailydelivery/dailydelivery',
    })
  },
  //进入公告详情
  oNnoticeDetailsTap: function(e) {
    wx.navigateTo({
      url: '../noticeDetails/noticeDetails',
    })
  },
  //跳入分类页面
  onClassifyTap: function(e) {
    wx.switchTab({
      url: '../classify/classify',
    })
  },
  //申请会员专享价
  onVipmemberTap: function(e) {
    wx.switchTab({
      url: '../vipmember/vipmember',
    })
  },
  //添加购物车
  addCarTap: function(e) {
    var that = this;
    var shuzi = wx.getStorageSync("number") || 0;
    var number = shuzi + 1
    that.setData({
      number: number
    })
    wx.setStorageSync("number", number);
    //微信小程序 tabbar 上面设置消息数目等
    if (wx.getStorageSync("number") != 0) {
      wx.setTabBarBadge({
        index: 3,
        text: String(wx.getStorageSync("number"))

      })
    }
    var dataInfo = {
      id: e.currentTarget.dataset.id,
      image: e.currentTarget.dataset.image,
      name: e.currentTarget.dataset.name,
      price: e.currentTarget.dataset.price,
      subtitle: e.currentTarget.dataset.subtitle,
      vip_price: e.currentTarget.dataset.vipprice,
      selectStatus: false, //购物车做删除时候用
      number: 1 //加减数量
    }
    utils.uniqueSearchRecord(dataInfo);
  },
  lll: function(e) {
    var that = this;
    if (that.data.indexgoods != undefined) {
      var indexgoods = that.data.indexgoods;
      for (var j in indexgoods) {
        for (var i in indexgoods[j].goods_list) {
          indexgoods[j].goods_list[i].number = 0;
          for (var k in wx.getStorageSync("listPost")) {
            if (wx.getStorageSync("listPost")[k].id == indexgoods[j].goods_list[i].id) {
              indexgoods[j].goods_list[i].number = wx.getStorageSync("listPost")[k].number;
            }
          }
        }
      }
      that.setData({
        indexgoods: indexgoods
      })
    }
  },
  lll2: function(e) {
    var that = this;
    if (that.data.ategoryList != undefined) {
      var ategoryList = that.data.ategoryList;
      for (var j in ategoryList) {
        for (var i in ategoryList[j].goods_list) {
          ategoryList[j].goods_list[i].number = 0;
          for (var k in wx.getStorageSync("listPost")) {
            if (wx.getStorageSync("listPost")[k].id == ategoryList[j].goods_list[i].id) {
              ategoryList[j].goods_list[i].number = wx.getStorageSync("listPost")[k].number;
            }
          }
        }
      }
      that.setData({
        ategoryList: ategoryList
      })
    }
  },
  //首页下方的商品列表不涉及分页
  indexgoodslist: function(e) {
    var that = this;
    utils.http("/api/v1/index/index_goods_list", {}, function(res) {
      for (var j in res.datas) {
        for (var i in res.datas[j].goods_list) {
          res.datas[j].goods_list[i].number = 0;
        }
      }
      that.setData({
        indexgoods: res.datas
      })
      that.lll();
    })
  },
  //根据分类获取商品 
  ategoryGoodsList: function() {
    var that = this;
    utils.showLoading();
    utils.http("/api/v1/goods/category_goods_list", {
      category_id: that.data.categoryId,
    }, function(res) {
      utils.hideLoading();
      for (var j in res.datas) {
        for (var i in res.datas[j].goods_list) {
          res.datas[j].goods_list[i].number = 0;
        }
      }
      that.setData({
        ategoryList: res.datas
      })
      that.lll2();
    })
  },
  //封装数据库加数据
  pervCtion: function(parameter) {
    var that = parameter.that;
    var itemslist = parameter.itemslist;
    var index = parameter.index;
    var ind = parameter.ind;
    var num = parameter.num;
    var shuzi = wx.getStorageSync("number") || 0;
    var number = shuzi + 1
    that.setData({
      number: number
    })
    wx.setStorageSync("number", number);
    //微信小程序 tabbar 上面设置消息数目等
    if (wx.getStorageSync("number") != 0) {
      wx.setTabBarBadge({
        index: 3,
        text: String(wx.getStorageSync("number"))
      })
    }
    var dataInfo = parameter.dataInfo;
    itemslist[ind]['goods_list'][index].number = itemslist[ind]['goods_list'][index].number + 1;
    utils.uniqueSearchRecord(dataInfo);
    return itemslist;

  },
  //封装数据库减数据
  nextCtion: function(parameter) {
    var that = parameter.that;
    var itemslist = parameter.itemslist;
    var index = parameter.index;
    var ind = parameter.ind;
    if (itemslist[ind]['goods_list'][index].number > 0) {
      itemslist[ind]['goods_list'][index].number = itemslist[ind]['goods_list'][index].number - 1;
      var nowStorage = wx.getStorageSync("listPost");
      for (var i in nowStorage) {
        if (nowStorage[i].id == itemslist[ind]['goods_list'][index].id) {
          nowStorage[i].number = nowStorage[i].number - 1;
          if (nowStorage[i].number == 0) {
            nowStorage.splice(i, 1);
          }
        }
      }
      that.setData({
        number: wx.getStorageSync("number") - 1,
      })
      wx.setStorageSync("listPost", nowStorage)
      wx.setStorageSync("number", that.data.number);
      // //微信小程序 tabbar 上面设置消息数目等
      if (wx.getStorageSync("number") != 0) {
        wx.setTabBarBadge({
          index: 3,
          text: String(wx.getStorageSync("number"))
        })
      } else {
        wx.removeTabBarBadge({
          index: 3
        })
      }
      return itemslist;
    } else {
      utils.message("该宝贝宝贝不能减少哦~");
    }
  },
  //加数量
  onPrevTap: function(e) {
    var that = this;
    var dataInfo = {
      id: e.currentTarget.dataset.id,
      image: e.currentTarget.dataset.image,
      name: e.currentTarget.dataset.name,
      price: e.currentTarget.dataset.price,
      subtitle: e.currentTarget.dataset.subtitle,
      vip_price: e.currentTarget.dataset.vipprice,
      selectStatus: false, //购物车做删除时候用
      number: 1 //加减数量
    }
    var parameter = {
      that: that,
      itemslist: that.data.indexgoods,
      index: e.currentTarget.dataset.index,
      ind: e.currentTarget.dataset.ind,
      dataInfo: dataInfo,
    }

    that.setData({
      indexgoods: that.pervCtion(parameter),
    })
  },
  //减数量
  onNextTap: function(e) {
    var that = this;
    var parameter = {
      that: that,
      itemslist: that.data.indexgoods,
      index: e.currentTarget.dataset.index,
      ind: e.currentTarget.dataset.ind,
    }
    that.setData({
      indexgoods: that.nextCtion(parameter),
    })
  },
  //加数量
  onPrevTap1: function(e) {
    var that = this;
    var dataInfo = {
      id: e.currentTarget.dataset.id,
      image: e.currentTarget.dataset.image,
      name: e.currentTarget.dataset.name,
      price: e.currentTarget.dataset.price,
      subtitle: e.currentTarget.dataset.subtitle,
      vip_price: e.currentTarget.dataset.vipprice,
      selectStatus: false, //购物车做删除时候用
      number: 1 //加减数量
    }
    var parameter = {
      that: that,
      itemslist: that.data.ategoryList,
      index: e.currentTarget.dataset.index,
      ind: e.currentTarget.dataset.ind,
      dataInfo: dataInfo,
    }
    that.setData({
      ategoryList: that.pervCtion(parameter),
    })
  },
  //减数量
  onNextTap1: function(e) {
    var that = this;
    var parameter = {
      that: that,
      itemslist: that.data.ategoryList,
      index: e.currentTarget.dataset.index,
      ind: e.currentTarget.dataset.ind,
    }
    that.setData({
      ategoryList: that.nextCtion(parameter),
    })
  },
  noMiaoConfirmoder: function(e) {
    var that = this;
    var status = that.data.spikeData[that.data.currentTab1].status;
    if (status == 0) {
      wx.showToast({
        title: '秒杀活动还未开始哦~',
        icon: 'none'
      });
      return;
    }

    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var spikeGoodsItem = that.data.spikegoodsData[index];
    var goodsList = [{
      spec_id: spikeGoodsItem.spec_id,
      number: 1,
      selectStatus: true,
      name: spikeGoodsItem.goods_info.name,
      image: spikeGoodsItem.goods_info.image,
      subtitle: spikeGoodsItem.goods_info.subtitle,
      spec_price: spikeGoodsItem.price,
      spec_vip_price: spikeGoodsItem.price,
      spec_stock: spikeGoodsItem.day_stock,
      spec_name: spikeGoodsItem.spec_info.spec_name
    }];
    wx.setStorageSync('spikeGoods', goodsList);
    var url = '/pages/confirmorder/confirmorder?type=1&spike_id=' + id;
    wx.navigateTo({
      url
    });
    return;
    var id = e.currentTarget.dataset.id;
    var goodsid = e.currentTarget.dataset.goodsid;
    var image = e.currentTarget.dataset.image;
    var name = e.currentTarget.dataset.name;
    var subtitle = e.currentTarget.dataset.subtitle;
    var price = e.currentTarget.dataset.price;
    wx.navigateTo({
      url: '../miaoConfirmoder/miaoConfirmoder?id=' + id + "&goodsid=" + goodsid + "&price=" + price + "&num=1" + "&name=" + name + "&subtitle=" + subtitle + "&image=" + image,
    })
  },
  //授权登陆 判断用户状态
  bindGetUserInfo: function(e) {
    console.log(e);
    var that = this
    if (e.detail.errMsg == "getUserInfo:ok") {
      console.log(e.target.dataset.id)
      var data = {
        nickname: e.detail.userInfo.nickName,
        sex: e.detail.userInfo.gender,
        avatar: e.detail.userInfo.avatarUrl
      }
      app.memberModify(data, (res) => {
        if (e.target.dataset.id == 0) {
          that.personalInfo();
        }
        if (e.target.dataset.id == 1) {
          that.personalInfo();
          wx.navigateTo({
            url: '../login/login?logintype=' + e.target.dataset.id,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
        }
        if (e.target.dataset.id == 2) {
          that.personalInfo();
          wx.navigateTo({
            url: '../login/login?logintype=' + e.target.dataset.id,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
        }
        wx.setStorage({
          key: 'last_login_time',
          data: Date.parse(new Date()) / 1000,
        })
      });
    }
  },
	//所有的商品列表
	goodslist: function () {
		var that = this;
		utils.showLoading();
		utils.http("/api/v1/goods/goods_list", {
			keyword:"",
			page: that.data.currentPage
		}, function (res) {
			utils.hideLoading();
			var allpost = that.data.allListData;
			if (allpost == undefined) {
				allpost = [];
			}
			for (var i in res.datas) {
				res.datas[i].number = 0;
				allpost.push(res.datas[i])
			}
			if (res.datas.length < 10) {
				that.setData({
					tishi_title: '已加载全部',
				});
			} else {
				that.setData({
					tishi_title: '加载更多',
				});
			}
			that.setData({
				allListData: allpost,
				ready: res.datas.length == 0 ? 1 : 2,
			})
			console.log(that.data.allListData)
		})
	},
  //获取优惠券信息 
  couponList: function(e) {
    var that = this;
    utils.http("/api/v1/coupon/coupon_one", {}, function(res) {
      that.setData({
        coupon: res.datas
      })
    })
  },
  // 收取优惠券
  onGetCouponTap: function(e) {
    var that = this;
    utils.http("/api/v1/coupon/get_coupon", {
      coupon_id: e.currentTarget.dataset.id
    }, function(res) {
      if (res.state == 1) {
        that.setData({
          isCoupon: true
        })
        that.couponList();
      } else {
        utils.message(res.datas)
      }
    })
  },
  //跳转优惠卷
  onCouponTap: function(e) {
    wx.navigateTo({
      url: '../personal/personalcoupon/personalcoupon',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  //关闭优惠券
  closeCouponTap: function(e) {
    var that = this;
    that.setData({
      isCoupon: true
    })
  },
  onKillPriceTap: function() {
    wx.navigateTo({
      url: '/pages/killPrice/killPrice',
    })
  },
  couponBuy: function() {
    wx.navigateTo({
      url: '/pages/personal/couponConfirm/couponConfirm',
    })
  },
  onPullDownRefresh: function() {
    var that = this;
	that.setData({
		allListData:[],
		currentPage:1
	})
	  that.ategoryGoodsList()
    that.setData({
      q: null,
    }, function() {
      that._load();
      setTimeout(function() {
        wx.stopPullDownRefresh();
      }, 500);
    });
  },
	/**
	  * 页面上拉触底事件的处理函数
	  */
	onReachBottom: function () {
		var that = this;
		if (that.data.ready == 2) {
			var page = that.data.currentPage + 1
			that.setData({
				currentPage: page,
			})
			that.goodslist()
		}

	},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }

})